<template>
	<view class="login">

		<!-- 顶部背景 -->
		<view class="bg_img">
			<image style="width: 100%;height: 100%;" mode="aspectFill" :src="xcxImgUrl && xcxImgUrl+'login/bg_top.svg'">
			</image>
		</view>

		<!-- 主题内容 -->
		<view class="main">
			<!-- 切换卡 -->
			<view>
				<text class="login_go" :class="textIndex == 1 ? 'actives' : ''" style="margin-right: 20rpx;"
					@click="selectText(1)">登录</text>
				<!-- <text class="login_go" :class="textIndex == 2 ? 'active' : ''" @click="selectText(2)">注册</text> -->
			</view>
			<u-input v-model="inputVal" :maxlength="clickType == 4 ? 6 : 10" ></u-input>
			<!-- 表单内容 -->
			<view class="main_form">
				<u--form labelPosition='top' :model="userInfo" :rules="rules" labelWidth="180rpx" ref="form">
					<u-form-item label="名称" v-if="textIndex == 2" borderBottom prop="name" ref="item">
						<u--input type="text" maxlength="20" v-model="userInfo.name" placeholder="请输入名称" border="none">
						</u--input>
					</u-form-item>
					<u-form-item label="手机号码" style="margin-bottom: 20rpx;" borderBottom prop="phone" ref="item">
						<u--input maxlength="11" type='number' v-model="userInfo.phone" placeholder="请输入手机号码"
							border="none">
						</u--input>
					</u-form-item>
					<u-form-item label="验证码" v-if="phoneIndex == 1 || textIndex == 2" borderBottom prop="authCode"
						ref="item">

						<!-- #ifndef APP-NVUE -->
						<u-input border="none" type="number" v-model="userInfo.authCode" placeholder="请填写验证码">
							<!-- #endif -->
							<!-- #ifdef APP-NVUE -->
							<u--input border="none" type="number" v-model="userInfo.authCode" placeholder="请填写验证码">
								<!-- #endif -->

								<template slot="suffix">
									<u-code ref="uCode" @change="codeChange" seconds="20" changeText="X秒重新获取"></u-code>
									<text @tap="getCode" class="yzm">{{tips}}
									</text>
								</template>
								<!-- #ifndef APP-NVUE -->
						</u-input>
						<!-- #endif -->
						<!-- #ifdef APP-NVUE -->
						</u--input>
						<!-- #endif -->


						<!-- <u-input
							placeholder="请输入验证码"
							border="none">
							<template slot="suffix">
								<u-code ref="uCode"
									seconds="20"
									changeText="X秒重新获取"></u-code>
								<text class="yzm">获取验证码</text>
							</template>
						</u-input> -->
					</u-form-item>
					<u-form-item label="密码" v-if="phoneIndex == 2 " borderBottom prop="password" ref="item">
						<u--input type="password" v-model="userInfo.password" placeholder="请输入密码" border="none">
						</u--input>
					</u-form-item>
				</u--form>
			</view>

			<!-- 登陆 -->
			<view @click="save" class="login_btn">
				{{textIndex ==1 ? '登录' : '注册'}}
			</view>

			<view class="agreement">
				<!-- <checkbox-group @change="changeChecked">
					<checkbox style="
					transform:scale(0.7);
					" value="1" color="#ec4141"></checkbox>
				</checkbox-group> -->
				<view class="custom_checkbox" style="display: flex;align-items: center;label-size:100px"
					:class="{active :checked[0] }">
					<!-- <checkbox @click="tapAllChecked" :checked="AllChecked" color="#ec4141"
						style="transform:scale(0.7);border-radius: 50%;"></checkbox> -->
					<u-checkbox-group v-model="checked" @change="changeChecked">
						<u-checkbox :name="true"></u-checkbox>
					</u-checkbox-group>
				</view>
				已阅读并同意《
				<text style="color:#ec4141 ;" @tap="navTo(1)">用户服务协议</text>
				》和《
				<text style="color:#ec4141 ;" @tap="navTo(2)">隐私协议</text>》
			</view>

			<!-- 其他登陆方式 -->
			<view class="other" v-if="textIndex == 1">
				<view class="other_title">
					其他登录方式
				</view>
				<view class="other_item">
					<view v-if="phoneIndex == 1" class="item_one" @click="clickPassword(1)">
						<image class="other_img" :src="xcxImgUrl && xcxImgUrl+'login/password.svg'"></image>
						<text class="item_text">密码登录</text>
					</view>
					<view v-if="phoneIndex == 2" class="item_one" @click="clickPassword(2)">
						<image class="other_img" :src="xcxImgUrl && xcxImgUrl+'login/phone.svg'"></image>
						<text class="item_text">手机登录</text>
					</view>
					<!-- <view class="item_one" @click="wxlogin">
						<image class="other_img" src="@/static/login/wx_img.svg"></image>
						<text class="item_text">微信登录</text>
					</view> -->
				</view>
			</view>
		</view>
		<textarea placeholder-style="color:#F76260" v-model='remark' placeholder="占位符字体是红色的"/>
		<test></test>
	</view>
</template>

<script>
	import {
		sendVerificationCode,
		login,
		getWechatOpenId,
		goLogin,
		registerApi,
		changeBinding
	} from '@/api/global.js'
	import {
		updateMallMemberInfo
	} from '@/api/setting.js'
	export default {
		data() {
			return {
				remark: '12',
				clickType: 4,
				inputVal: '',
				checked: [],
				textIndex: 1, //当前显示下标 是注册还是登录 1.登录 2.注册
				phoneIndex: 1, //区分是验证码登录还是密码登录 1.验证码 2.密码
				rules: {
					'phone': [{
							type: 'string',
							required: true,
							message: '请输入手机号码',
							trigger: ['blur', 'change']
						}, {
							len: 11,
							message: '手机号码长度为11位',
							trigger: ['blur', 'change']
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// uni.$u.test.mobile()就是返回true或者false的
								return uni.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						}
					],
					'name': [{
						type: 'string',
						required: true,
						message: '请填写名称',
						trigger: ['blur', 'change']
					}],
					'authCode': [{
						type: 'string',
						required: true,
						message: '请填写验证码',
						trigger: ['blur', 'change']
					}],
					'password': [{
						type: 'string',
						required: true,
						message: '请输入密码',
						trigger: ['blur', 'change']
					}],
				},
				userInfo: {
					phone: '',
					authCode: '',
					password: '',
					name: ``
				},
				tips: '获取验证码',
				type: '' //区分从哪个地方跳转到登录 type= noVisitorStatus 没开启游客模式 到登录完成验证码绑定 type = outLogin 退出其他人用密码登录
			};
		},
		async onLoad(options) {
			let code = this.getUrlParams('code');
			if (code) {
				let result = await getWechatOpenId({
					code,
					mark: 2 //标记[1.小程序 2.网页公众号]
				})
				if (result.code == 2000) {
					let openId = result.data.info.openId;
					uni.setStorageSync('wxh5OpenId', openId);
					let res = await goLogin({
						branchId: this.$store.state.branchId, //分支机构id[关联分支机构表]
						bussinessId: this.$store.state.bussinessId, //商户id[关联商户表]
						accountId: this.$store.state.accountId, //账套id[关联账套表]
						openId: openId, //微信openId
						uuid: openId
					})
					if (res.code == 2000) {
						console.log(res);
						// 先判断是否是会员 是会员 直接进 不是会员 在判断是否开启游客模式
						if (res?.data?.info?.MallMember?.status == 1) {
							//根据状态判断是否是开启游客模式 开启则进入首页 没开启则去登录 绑定手机号
							if (res?.data?.info?.visitorStatus == 2) { //1.开启 2.没有开启
								uni.navigateTo({
									url: '/pages/login/login?type=noVisitorStatus'
								})
								return;
							}
							// 存储账户信息
							uni.setStorageSync('visitorLoginInfo', JSON.stringify(res.data.info))
							//存储临时token
							uni.setStorageSync('visitorAccessToken', JSON.stringify(res.data.info.accessToken))
							this.$store.commit('updateToken', res.data.info.accessToken)
							uni.switchTab({
								url: '/pages/home/home'
							});
						} else {
							if (!uni.getStorageSync('visitorLoginInfo')) {
								uni.navigateTo({
									url: '/pages/login/login?type=noVisitorStatus'
								})
							} else {
								console.log('12')
								//获取商城系统参数设置
								this.$store.dispatch('configSetting/getSetting')
								this.$isResolve() //标记等这走完 转同步在main.js中挂载 home首页监听
							}
							uni.switchTab({
								url: '/pages/home/home'
							});
						}
					} else {
						this.Utils.toast(`${res.msg}`);
					}
				} else {
					alert(`${result.msg}`);
				}
			}
			//接收值
			this.type = options?.type || ''
			//如果type = noVisitorStatus
			if (this.type == 'noVisitorStatus') { //只显示验证码
				this.phoneIndex = 1
			}
			//如果type = outLogin
			if (this.type == 'outLogin') { //只显示密码 
				this.phoneIndex = 2
			}

		},
		methods: {
			inputValue(value) {
    if (value.length > 6) { // 如果输入值超过六位
      this.$nextTick(()=>{
		this.inputVal = value.slice(0, 6);
	  }) // 截取前六位字符
    }
	console.log(this.inputVal,value)
  },
			isWeixin() {
				let ua = window.navigator.userAgent.toLowerCase();
				if (ua.match(/MicroMessenger/i) == 'micromessenger') {
					return true;
				} else {
					return false;
				}
			},
			changeChecked(e) {
				console.log(e)
				this.checked = e;
			},
			navTo(type) {
				if (type == 1) {
					uni.navigateTo({
						url: `/pages/login/user_server`
					})
				} else if (type == 2) {
					uni.navigateTo({
						url: `/pages/login/policy`
					})
				}
			},
			//点击登录
			async save() {
				//校验必填
				console.log(this.phoneIndex,'this.phoneIndex')
				let config = await this.$refs.form.validate()
				if (config) {
					//验证码登录 相当于绑定手机号
					if (this.phoneIndex == 1) {
						if (this.checked && !this.checked.length) {
							this.Utils.toast(`请先勾选用户协议与隐私协议`);
							return;
						}
						if (this.textIndex == 1) {
							let resr = await login({
								branchId: this.$store.state.branchId, //分支机构id[关联分支机构表]
								bussinessId: this.$store.state.bussinessId, //商户id[关联商户表]
								accountId: this.$store.state.accountId, //账套id[关联账套表]
								source: 1,
								// #ifdef MP-WEIXIN 
								source: 1, //来源[1：微信小程序 2：APP]
								// #endif
								// #ifdef APP-PLUS
								source: 2, //来源[1：微信小程序 2：APP]
								// #endif
								phone: this.userInfo.phone, //手机号
								verificationCode: this.userInfo.authCode,
							})
							console.log(resr);
							if (resr.code == 2000) {
								// 存储账户信息
								uni.setStorageSync('visitorLoginInfo', JSON.stringify(resr.data.info))
								//存储临时token
								uni.setStorageSync('visitorAccessToken', JSON.stringify(resr.data.info.accessToken))
								uni.setStorageSync('expirDate', JSON.stringify({
									time: new Date().getTime() + this.expireDate
								}));
								// this.Utils.toast(`绑定登录成功`)
								// setTimeout(() => {
								// 	uni.switchTab({
								// 		url: '/pages/home/home'
								// 	})
								// }, 500)
								if (resr.data.info.MallMember.openId != uni.getStorageSync('wxOpenId')) {
									uni.showModal({
										title: `提示`,
										content: `是否绑定当前微信`,
										success: async (r) => {
											console.log(r)
											console.log(uni.getStorageSync('wxOpenId'),'openId');
											if (r.confirm) {
												let result = await changeBinding({
													openId: uni.getStorageSync('wxOpenId')
												});
												if (result.code == 2000) {
													this.Utils.toast(`绑定成功`);
													setTimeout(() => {
														uni.switchTab({
															url: '/pages/home/home'
														})
													}, 500)
												} else {
													this.Utils.toast(`${result.msg}`);
												}
												// this.Utils.toast(`登录成功`)
											} else {
												console.log(1111111111);
												this.Utils.toast(`登录成功`);
												setTimeout(() => {
													uni.switchTab({
														url: '/pages/home/home'
													})
												}, 500)
											}
										}
									})
								} else{
									this.Utils.toast(`登录成功`);
									setTimeout(() => {
										uni.switchTab({
											url: '/pages/home/home'
										})
									}, 500)
								}
							} else {
								this.Utils.toast(`${resr.msg}`)
							}
						}
					}
					if (this.phoneIndex == 3) {
						if (this.checked && !this.checked.length) {
							this.Utils.toast(`请先勾选用户协议与隐私协议`);
							return;
						}
						let resr = await registerApi({
							branchId: this.$store.state.branchId, //分支机构id[关联分支机构表]
							bussinessId: this.$store.state.bussinessId, //商户id[关联商户表]
							accountId: this.$store.state.accountId, //账套id[关联账套表]
							name: this.userInfo.name, //名称
							phone: this.userInfo.phone, //手机号
							verificationCode: this.userInfo.authCode,
						})
						console.log(resr);
						if (resr.code == 2000) {
							this.Utils.toast(`注册成功`)
							this.textIndex = 1;
							this.phoneIndex = 2;
						} else {
							this.Utils.toast(`${resr.msg}`)
						}
					}
					//手机号密码登录 相当于登录其他人账号
					if (this.phoneIndex == 2) {
						if (this.checked && !this.checked.length) {
							this.Utils.toast(`请先勾选用户协议与隐私协议`);
							return;
						}
						let res = await login({
							branchId: this.$store.state.branchId, //分支机构id[关联分支机构表]
							bussinessId: this.$store.state.bussinessId, //商户id[关联商户表]
							accountId: this.$store.state.accountId, //账套id[关联账套表]
							source: 1,
							// #ifdef MP-WEIXIN 
							source: 1, //来源[1：微信小程序 2：APP]
							// #endif
							// #ifdef APP-PLUS
							source: 2, //来源[1：微信小程序 2：APP]
							// #endif
							phone: this.userInfo.phone, //手机号
							password: this.$md5(this.userInfo.password).toUpperCase(), //登录密码[MD5加密]
						})
						if (res.code == 2000) {
							// 存储账户信息
							uni.setStorageSync('visitorLoginInfo', JSON.stringify(res.data.info))
							//存储临时token
							uni.setStorageSync('visitorAccessToken', JSON.stringify(res.data.info.accessToken));
							uni.setStorageSync('expirDate', JSON.stringify({
								time: new Date().getTime() + this.expireDate
							}));
							console.log('uni.getStorageSync',res.data.info.MallMember.openId, uni.getStorageSync('wxOpenId'))
							if (res.data.info.MallMember.openId != uni.getStorageSync('wxOpenId')) {
								uni.showModal({
									title: `提示`,
									content: `是否绑定当前微信`,
									success: async (r) => {
										console.log(r)
										if (r.confirm) {
											let result = await changeBinding({
												openId: uni.getStorageSync('wxOpenId')
											});
											if (result.code == 2000) {
												this.Utils.toast(`绑定成功`);
												setTimeout(() => {
													uni.switchTab({
														url: '/pages/home/home'
													})
												}, 500)
											} else {
												this.Utils.toast(`${result.msg}`);
											}
											// this.Utils.toast(`登录成功`)
										} else {
											console.log(1111111111);
											this.Utils.toast(`登录成功`);
											setTimeout(() => {
												uni.switchTab({
													url: '/pages/home/home'
												})
											}, 500)
										}
									}
								})
							} else{
								this.Utils.toast(`登录成功`);
								setTimeout(() => {
									uni.switchTab({
										url: '/pages/home/home'
									})
								}, 500)
							}
						} else {
							this.Utils.toast(`${res.msg}`);
						}
					}
				}
			},
			//获取验证码
			getCode() {
				this.$refs.form.validateField('phone', (res) => {
					if (res.length == 0) {
						if (this.$refs.uCode.canGetCode) {
							// 模拟向后端请求验证码
							uni.showLoading({
								title: '正在获取验证码'
							})
							sendVerificationCode({
								phone: this.userInfo.phone,
								tag: 2
							}).then(resr => {
								if (resr.code == 2000) {
									uni.hideLoading();
									// 这里此提示会被this.start()方法中的提示覆盖
									uni.$u.toast('验证码已发送');
									// 通知验证码组件内部开始倒计时
									this.$refs.uCode.start();
								} else {
									uni.hideLoading();
									this.Utils.toast(`${resr.msg}`)
								}
							})

						} else {
							uni.$u.toast('倒计时结束后再发送');
						}
					}
				})

			},
			codeChange(text) {
				this.tips = text;
			},
			// 切换登陆还是注册
			selectText(index) {
				console.log(1);
				this.textIndex = index
				if (this.textIndex == 2) {
					this.phoneIndex = 3;
				} else {
					this.phoneIndex = 2;
				}
			},
			getUrlParams(name) {
				let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
				console.log(window.location);
				let r = window.location?.search.substr(1).match(reg);
				if (r != null) {
					return decodeURI(r[2])
				}
				return null;
			},
			wxlogin() {
				if (this.isWeixin()) {
					let local = encodeURIComponent(window.location.href); //获取当前页面地址
					let Appid = `wx497d5778bf1895b8`;
					window.location.href =
						"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
						Appid + ///你APP申请的APPId，每个app都有个ID是识别你app的方式
						"&redirect_uri=" +
						local +
						"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
				} else {
					this.Utils.toast(`请在微信浏览器运行`);
				}
			},
			//切换验证码密码登录
			clickPassword(index) {
				this.$refs.form.clearValidate();
				if (index == 1) {
					this.phoneIndex = 2
				}
				if (index == 2) {
					this.phoneIndex = 1
				}
			},

		}

	}
</script>

<style lang="scss">
	.login {
		position: relative;

	}

	.bg_img {
		height: 400rpx;
		width: 100%;
		position: absolute;
		pointer-events: none;
		top: 0;
		left: 0;
	}

	.main {
		box-sizing: border-box;
		padding: 200rpx 60rpx 0 60rpx;
		width: 100%;

		.login_go {
			color: $text_color_808080;
			font-size: $font_size_18;
			font-weight: bold;
		}

		.actives {
			font-size: $font_size_20;
			color: $text_color_333;
			position: relative;
		}

		.actives::after {
			display: block;
			width: 56rpx;
			height: 8rpx;
			background: linear-gradient(90deg, rgba(236, 65, 65, 1) 0%, rgba(251, 154, 154, 1) 99%);
			content: '';
			position: absolute;
			top: 60rpx;
			left: 10rpx;
			border-radius: 4rpx;
		}

		.main_form {
			margin-top: 60rpx;
			width: 100%;
		}

		.main_form /deep/.u-form-item__body__left__content__label {
			color: $text_color_333 !important;
			font-size: $font_size_14 !important;
			font-weight: bold;
			margin-bottom: 20rpx;
		}

		.main_form /deep/.input-placeholder {
			font-size: $font_size_14 !important;
		}

		.yzm {
			color: $text_color_ec4141;
			font-size: $font_size_14;
			padding-left: 20rpx;
			border-left: 1px solid #CCCCCC !important;
		}

		.login_btn {
			margin-top: 60rpx;
			height: 88rpx;
			width: 100%;
			border-radius: 200rpx;
			background: linear-gradient(89.5527352405209deg, rgba(236, 65, 65, 1) 0%, rgba(255, 146, 146, 1) 99%);
			box-shadow: 0 10rpx 10rpx rgba(236, 65, 65, .3);
			line-height: 88rpx;
			text-align: center;
			color: $text_color_fff;
			font-weight: bold;

		}

		.agreement {
			font-size: $font_size_12;
			color: $text_color_999;
			margin-top: 20rpx;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.agreement /deep/.uni-checkbox-input {
			border-radius: 50% !important;
			border-color: rgb(236, 65, 65) !important;
		}

		.agreement /deep/.u-icon__icon.uicon-checkbox-mark {
			font-weight: bold !important;
		}

		.other {
			margin-top: 150rpx;
			display: flex;
			flex-direction: column;
			align-items: center;

			.other_title {
				font-size: $font_size_12;
				color: $text_color_333;
				margin-bottom: 30rpx;
			}

			.other_item {
				display: flex;
				// gap: 40rpx;
				// width: 250rpx;
			}

			.other_img {
				display: block;
				width: 80rpx;
				height: 80rpx;
			}

			.item_one {
				display: flex;
				flex-direction: column;
				align-items: center;
				margin: 0 16rpx;
			}

			.item_text {
				font-size: $font_size_12;
				color: $text_color_999;
				margin-top: 10rpx;
			}
		}
	}
</style>